package com.cskaoyan.service.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.service.AdminService;
import com.cskaoyan.utils.CommonUtil;
import com.cskaoyan.utils.EncryptUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @PROJECT_NAME: market_34th
 * @DESCRIPTION:
 * @Author: qiu
 * @DATE: 2021/10/18 21:45
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminMapper adminMapper;

    /**
     * 图片上传功能
     * @param username
     * @param param
     * @return
     */
    @Override
    public BasePageData<Admin> query(String username, BaseParam param) {
        // 配置分页信息
        PageHelper.startPage(param.getPage(), param.getLimit());
        // 构造条件的对象
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        if (CommonUtil.isStrNotEmpty(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        // 设置排序
        example.setOrderByClause(param.getSort() + " " + param.getOrder());
        List<Admin> admins = adminMapper.selectByExample(example);

        return BasePageData.ok(admins);
    }

    /**
     * 新增管理员
     * @param admin
     * @return
     */
    @Override
    public Admin create4log(Admin admin) {

        admin.setPassword(EncryptUtil.MD5(admin.getPassword()));
        admin.setAddTime(new Date());
        admin.setUpdateTime(new Date());

        AdminExample example = new AdminExample();
        adminMapper.insertSelective(admin);

        return admin;
    }

    /**
     * 删除管理员
     * @param admin
     */
    @Override
    public void delete4log(Admin admin) {
        adminMapper.deleteByPrimaryKey(admin.getId());
    }

    /**
     * 修改管理员
     * @param admin
     * @return
     */
    @Override
    public Admin update4log(Admin admin) {
        if(admin.getPassword().length() < 25){
            admin.setPassword(EncryptUtil.MD5(admin.getPassword()));
        }
        // 需要更新修改时间
        admin.setUpdateTime(new Date());

        adminMapper.updateByPrimaryKeySelective(admin);
        return admin;
    }
}
